/*
* @Author: Administrator
* @Date:   2017-12-22 14:27:05
* @Last Modified by:   'baijiwei'
* @Last Modified time: 2018-01-02 16:39:37
*/
const path = require('path');
const axios = require('axios');
const memoryFs=require("memory-fs");
const serverConfig = require('../../webpack.server.config.js');
// 解决react异步问题
const vm = require('vm');
const NativeModule = require('module')
const webpack = require('webpack');
const httpProxy = require('http-proxy-middleware')
const mfs = new memoryFs();
const serverCompiler = webpack(serverConfig);
const serverRender = require('./server_render')


const getTemplate = () => {
  return new Promise((resolve, reject) =>{
    axios.get('http://localhost:8087/dist/index.ejs').then((res) => {
      resolve(res.data)
    }).catch(reject)
  })
}
const getModuleFromString = (bundle,filename) => {
  const m = { exports: {} }
  const wrapper = NativeModule.wrap(bundle)
  const script = new vm.Script(wrapper,{
    filename: filename,
    displayErrors: true,
  })
  const result = script.runInThisContext()
  result.call(m.exports, m.exports, require, m)
  return m

}
let bundleModule,html
serverCompiler.outputFileSystem = mfs;
serverCompiler.watch({}, (error,stats) => {
  if(error) throw error
  else {
    stats=stats.toJson();
    stats.errors.forEach(err => console.error(err))
    stats.warnings.forEach(warn => console.error(warn))
    const bundlePath=path.join(serverConfig.output.path,serverConfig.output.filename);
    const bundle = mfs.readFileSync(bundlePath,'utf-8');
    bundleModule = getModuleFromString(bundle,'server_entry.js').exports;
  }
})
const serverDev = function (app) {
  app.use('/dist',httpProxy({
    target:"http://localhost:8087"
  }))
  app.get('*', function(req,res,next){
    if(!bundleModule){
      res.status(500).send('等待编译')
      res.end()
      return
    }
    getTemplate().then((template) =>{
      return serverRender(bundleModule, template, req, res)
    }).catch(next)
  })
}
module.exports = serverDev;
